module ui {

    export class TableUI extends egret.DisplayObjectContainer {

        private items: Array<egret.DisplayObject> = [];

        private col: number = 0;

        private xSpacing: number = 50;
        private ySpacing: number = 50;

        public constructor(col: number, xSpacing: number = 30, ySpacing: number = 20) {
            super();
            this.col = col;
            this.xSpacing = xSpacing;
            this.ySpacing = ySpacing;
        }

        public add(item: egret.DisplayObject): void {
            this.items.push(item);
        }

        private itemWidth: number = 0;

        public setItemWidth(itemWidth: number): void {
            this.itemWidth = itemWidth;
        }

        public relayout(): void {
            let colIdx: number = 0;
            let xpos: number = 0;
            let ypos: number = 0;
            let widthInch: number = 0;
            let heightInch: number = 0;
            for (let i: number = 0; i < this.items.length; i++) {
                let item: egret.DisplayObject = this.items[i];
                if (widthInch < 1) {
                    if (this.itemWidth > 0) {
                        widthInch = this.itemWidth;
                    } else {
                        widthInch = item.width;
                    }
                    heightInch = item.height;
                }
                item.x = xpos;
                item.y = ypos;
                colIdx = ++colIdx % this.col;
                if (colIdx > 0) {
                    xpos += widthInch + this.xSpacing;
                } else {
                    xpos = 0;
                    ypos += heightInch + this.ySpacing;
                    egret.log("ypos:", ypos);
                    colIdx = 0;
                }
                this.addChild(item);
            }
        }

    }

}